package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.MessageService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.List;

@WebServlet("/emailGetFriend")
public class EmailGetFriend extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        Response.setCorsHeaders(response);
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 获取请求参数
            String username = request.getParameter("username");
            System.out.println(username);

            // 连接数据库并查询好友列表
            List<String> friends= MessageService.getFriends(username);
            System.out.println(friends);

            // 返回响应
            if (friends != null) {
                out.print(new ObjectMapper().writeValueAsString(friends));
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                out.print("[]"); // 返回空数组
                response.setStatus(HttpServletResponse.SC_OK);
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("[]"); // 返回空数组
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
